
const ENV = 'prod';
const TASK_NAME = '美团外卖';

//检测无障碍模式是否启用
auto.waitFor();
//保持屏幕常量
device.keepScreenOn();

main();

function main() {
    outputMessage('任务开始');
    while (true) {
        try {
            if (!checkAppExist()) throw new Error('应用未安装');
            killApp(TASK_NAME);
            sleep(3000);
            launchApp(TASK_NAME);
            sleep(15000);
            let updateButton = id('wm_upgrade_force_cancel').findOnce();
            if (updateButton != null) {
                let updateRect = updateButton.bounds();
                click(updateRect.centerX(), updateRect.centerY());
                sleep(1500);
            } else {
                let centerButton = id('bottom_center_close_button').findOnce();
                if (centerButton != null) {
                    let centerRect = centerButton.bounds();
                    click(centerRect.centerX(), centerRect.centerY());
                    sleep(1500);
                }
            }
            let closeButton = id('close').findOnce();
            if (closeButton != null) {
                let closeRect = closeButton.bounds();
                click(closeRect.centerX(), closeRect.centerY());
                sleep(1500);
            }

            let dataMap = [];
            let medical = textStartsWith('买药').findOnce();
            if (medical != null) {
                let medicalRect = medical.bounds();
                click(medicalRect.centerX(), medicalRect.centerY() - 20);
                sleep(5500);
                let position = getPointByBL(device.width / 2, device.height * 0.5);
                click(position.x, position.y);
                sleep(3500);

                let shopName = [];
                for (let i = 0; i < 4; i++) {
                    if (shopName.length > 0) break;
                    findShop(shopName, dataMap);
                    swipeThePage();
                }
            } else {
                outputMessage('找不到买药按钮');
            }
            if (dataMap.length > 0) {
                saveLocation(dataMap);
            }
            outputMessage('任务结束');
            sleep(8000);
        } catch (e) {
            console.error(e);
            sleep(8000);
        }
    }
}

/**
 * 寻找店铺
 * @param {*} shopName 
 * @param {*} dataMap 
 */
function findShop(shopName, dataMap) {
    let dataList = idEndsWith('txt_poiList_adapter_name').find();
    for (let i = 0; i < 1; i++) {
        let data = dataList[i];
        let shopText = data.text();
        let saleNum = data.parent().parent().parent().child(1).child(0).child(0).child(1).text();
        if (shopName.indexOf(shopText) == -1) {
            let dataRect = data.bounds();
            if (dataRect.centerY() < device.height && dataRect.centerX() < device.width) {
                outputMessage('店铺名称: ' + shopText);
                shopName.push(shopText);
                click(dataRect.centerX(), dataRect.centerY());
                sleep(6500);
                //寻找药品
                findMedical(dataMap, {
                    shop: shopText,
                    sale: saleNum,
                    goods: []
                });
            }
        }
    }
}

/**
 * 寻找药品
 * @param {*} dataMap 
 */
function findMedical(dataMap, shopInfo) {
    //找药品
    let allCate = textEndsWith('全部分类').findOnce();
    if (allCate != null) {
        let allCateRect = allCate.bounds();
        click(allCateRect.centerX(), allCateRect.centerY());
        sleep(4500);
        let foodArr = [];
        //找上5页数据
        while (true) {
            findFoodDetail(foodArr, shopInfo);
            swipeThePage();
            //到达页面底部
            let bottom = textEndsWith('已经到底啦').findOnce();
            if (bottom != null) {
                break;
            }
        }
        dataMap.push(shopInfo);
    }
    back();
    sleep(3500);
    back();
    sleep(3500);
}

/**
 * 寻找物品详情
 * @param {*} foodArr
 */
function findFoodDetail(foodArr, shopInfo) {
    let foodList = idEndsWith('txt_stickyfoodList_adapter_food_name').find();
    for (let j = 0; j < foodList.length; j++) {
        let food = foodList[j];
        if (foodArr.indexOf(food.text()) == -1) { //还没记录
            let currentData = {
                name: food.text(),
                date: formatDate("yyyy-MM-dd hh:mm:ss", new Date())
            };
            foodArr.push(food.text());
            let foodBox = food.parent();
            if (foodBox.children().length > 4) {
                let saleBox = foodBox.child(2);
                let saleBoxChild = saleBox.children();
                for (let y = 0; y < saleBoxChild.length; y++) {
                    if (saleBoxChild[y].id() == 'com.sankuai.meituan.takeoutnew:id/tv_stickyfood_sold_count') {
                        currentData['sale'] = saleBoxChild[y].text();
                    }
                }
                let priceBox = foodBox.child(4);
                //找到了价格控件
                if (priceBox.id() == 'com.sankuai.meituan.takeoutnew:id/ll_price_layout') {
                    let priceChildrenBox = priceBox.children();
                    for (let x = 0; x < priceChildrenBox.length; x++) {
                        //现价
                        if (priceChildrenBox[x].id() == 'com.sankuai.meituan.takeoutnew:id/txt_stickyfoodList_adapter_food_price_fix') {
                            currentData['current_price'] = priceChildrenBox[x].text();
                        } else if (priceChildrenBox[x].id() == 'com.sankuai.meituan.takeoutnew:id/txt_stickyfoodList_adapter_food_original_price_fix') {
                            currentData['original_price'] = priceChildrenBox[x].text();
                        }
                    }
                }

            }
            shopInfo.goods.push(currentData);
        }
    }
}

/**
 * 按比例获取坐标点
 * @param {*} w 
 * @param {*} h 
 */
function getPointByBL(w, h) {
    let p = {};
    p.x = device.width * w;
    p.y = device.height * h;
    return p;
}

/**
 * 在控制台输出
 * @param {string} content 
 */
function outputMessage(content) {
    //只有测试环境才会输出
    if (ENV == "test" || ENV == "local") {
        log(content)
    } else {
        toast(content);
    }
}

/**
 * 翻页
 */
function swipeThePage() {
    outputMessage('翻页');
    let start_x = device.width / 2;
    let start_y = device.height * 0.8;
    let end_x = device.width / 2;
    let end_y = device.height * 0.2;

    gesture(300, [start_x, start_y], [end_x, end_y]);
    sleep(2000);
}

/**
 * 杀死app
 * @param {*} appName 
 */
function killApp(appName) {
    outputMessage('关闭后台进程');
    home();
    sleep(1500);
    launchApp(appName);
    sleep(10000);
    let packageName = currentPackage();
    app.openAppSetting(packageName);
    text(app.getAppName(packageName)).waitFor();
    sleep(2500);
    let is_sure = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOne();
    if (is_sure.enabled()) {
        let close = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOnce();
        if (close != null) {
            let rect = close.bounds();
            click(rect.centerX(), rect.centerY());
            sleep(1500);
        }
        close = textMatches(/(.*确.*|.*定.*)/).findOnce();
        if (close != null) {
            let rect = close.bounds();
            click(rect.centerX(), rect.centerY());
            sleep(1500);
        }
        log(app.getAppName(packageName) + "应用已被关闭");
        sleep(1000);
        back();
    } else {
        log(app.getAppName(packageName) + "应用不能被正常关闭或不在后台运行");
        back();
    }
    home();
}

/**
 * 检查app是否安装
 */
function checkAppExist() {
    let appName = app.getAppName('com.sankuai.meituan.takeoutnew');
    return appName == null ? false : true;
}

/**
 * 记录到本地
 * @param {*} data 
 */
function saveLocation(data) {
    outputMessage('记录数据');
    let jsonData = JSON.stringify(data);
    let date = formatDate("yyyy-MM-dd hh:mm:ss", new Date());
    let filename = date + '.txt';
    let path = "/sdcard/Download/" + filename;
    if (!files.exists(path)) {
        files.create(path);
    }
    files.write(path, jsonData);
}

function formatDate(fmt, date) {
    var o = {
        "M+": date.getMonth() + 1,                 //月份 
        "d+": date.getDate(),                    //日 
        "h+": date.getHours(),                   //小时 
        "m+": date.getMinutes(),                 //分 
        "s+": date.getSeconds(),                 //秒 
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
        "S": date.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}  